//
//  DRWebViewController.m
//  DoctorRen
//
//  Created by Lemon on 2018/11/19.
//

#import "DRWebViewController.h"
#import <Masonry/Masonry.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import <YYModel/YYModel.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>
#import <WebKit/WebKit.h>
#import <AFNetworking/AFNetworking.h>
#import <AVKit/AVKit.h>

@protocol DRJSExport <JSExport>

- (void)uploadImage:(NSInteger )type;

- (void) back;

//-(void)share:(NSString *) title text:(NSString *)text url:(NSString *)url icon:(NSString *)icon;

- (void) logout;

- (void) goLogin;

-(void) share;

-(void) goCatering;

@end



@interface DRWebViewController ()<UIWebViewDelegate, DRJSExport,UIImagePickerControllerDelegate,

UINavigationControllerDelegate ,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) JSContext *webJSContext;

@property (nonatomic, strong) UIImagePickerController *picker;

@end

@implementation DRWebViewController

-(void)dealloc{
    [_webView loadHTMLString:@"" baseURL:nil];
    [_webView stopLoading];
    if (_webView) {
        [_webView removeFromSuperview];
        _webView = nil;
    }
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
    
    NSLog(@"------------------------------");
    NSLog(@"DRWebViewController dealloc!!!");
    NSLog(@"------------------------------");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.bottom.mas_equalTo(0);
    }];
    self.view.clipsToBounds = YES;

}


- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self setKefuButtonHidden:YES];
    [self reloadToken];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
    [SVProgressHUD dismiss];
    [self setStatusBarBackgroundColor:[UIColor clearColor]];
}

-(void) reloadToken{
    NSMutableDictionary *params = [self.url getURLParameters];
    NSString *token = params[@"token"];
    if (![token isEqualToString: [DRLoginDataModel getUserToken]]) {
        NSLog(@"刷新webView");
        NSRange range = [self.url rangeOfString:[NSString stringWithFormat:@"token=%@",token]];
        NSString *newUrl = [self.url stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:@"token=%@",[DRLoginDataModel getUserToken]]];
        self.url = newUrl;
        [self.webView reload];
    }
}

- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

-(void)setUrl:(NSString *)url{
    _url = url;
    [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:_url]]];
}


-(UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.delegate = self;
        _webView.scrollView.clipsToBounds = YES;
        _webView.clipsToBounds = YES;
    }
    return  _webView;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
     JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.webJSContext = jsContext;

//    //自定义的JS对象，需要注入到context中
    WEAKSELF
    self.webJSContext[@"app"] = weakSelf;
    
    
    [SVProgressHUD dismiss];
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    [SVProgressHUD showWithStatus:@"正在加载..."];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL *url = [request URL];
    NSLog(@"url: %@",url);
    if ([[url scheme] isEqualToString:@"tel"]){
        NSString *res = [url resourceSpecifier];
        if ([res isEqualToString:@"back"]) {
            if ([self.webView canGoBack])
            {   // webView本身回退
                [self.webView goBack];
            }
            else
            {   // 原生回退
                [self.navigationController popViewControllerAnimated:YES];
            }
            
            return NO;
        }else if ([res isEqualToString:@"exit"]){
            //退出登录
            [self showLoginOutAlert];
            return NO;
        }
    }
    
    return YES;
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

-(void) showLoginOutAlert{
    WEAKSELF
    [self presentAlertViewWithTitle:@"是否退出登录？" message:@"" cancelTitle:@"取消" defaultTitle:@"确定" distinct:YES cancel:^{
        
    } confirm:^{
        [weakSelf logout];
    }];
}


-(void)uploadImage:(NSInteger)type{
    NSLog(@"%ld",type);
    //type = 0 ，可以上传视频 ，1 不可用
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择头像方式" message:@"" preferredStyle:(UIAlertControllerStyleActionSheet)];
    WEAKSELF
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            weakSelf.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [weakSelf presentViewController:weakSelf.picker animated:YES completion:nil];
        }else{
            
        }

    }];
    [alert addAction:action1];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            weakSelf.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            weakSelf.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
            weakSelf.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
//            self.picker.allowsEditing = YES;
            [weakSelf presentViewController:weakSelf.picker animated:YES completion:nil];
        }else{

        }
    }];
    [alert addAction:action2];
    if (type == 0) {
        UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"从视频库选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"从视频库选择");
            weakSelf.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            weakSelf.picker.mediaTypes = @[(NSString *)kUTTypeMovie];
            weakSelf.picker.allowsEditing = NO;
            
            [weakSelf presentViewController:weakSelf.picker animated:YES completion:nil];
        }];
         [alert addAction:action4];
    }
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action3];
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf presentViewController:alert animated:YES completion:nil];
    });
}


-(void)share{
    NSArray *args = [JSContext currentArguments];
    //创建分享参数
    NSLog(@"-------分享-----");
    NSLog(@"title:%@",args[0]);
    NSLog(@"text:%@",args[1]);
    NSLog(@"url:%@",args[2]);
    NSLog(@"icon:%@",args[3]);
    NSString *title = [args[0] toString] ? :@"";
    NSString *text = [args[1] toString] ? :@"";
    NSString *url = [args[2] toString]? : @"";
    NSString *icon = [args[3] toString] ? : @"";
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:text images:icon url:[NSURL URLWithString:url] title:title type:SSDKContentTypeAuto];
    
    SSUIShareSheetConfiguration *config = [[SSUIShareSheetConfiguration alloc] init];
//    config.interfaceOrientationMask = UIInterfaceOrientationMaskPortraitUpsideDown;
    //2、弹出ShareSDK分享菜单
    [ShareSDK showShareActionSheet:nil
                       customItems:@[@(SSDKPlatformTypeWechat),
                                     @(SSDKPlatformTypeQQ)]
                       shareParams:shareParams
                sheetConfiguration:config
                    onStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                        switch (state) {
                            case SSDKResponseStateSuccess:
                                [SVProgressHUD showSuccessWithStatus:@"分享成功!"];
                                NSLog(@"分享成功!");
                                break;
                            case SSDKResponseStateFail:
                                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.localizedDescription]];
                                NSLog(@"分享失败%@",error);
                                break;
                            case SSDKResponseStateCancel:
                                [SVProgressHUD showErrorWithStatus:@"分享已取消"];
                                NSLog(@"分享已取消");
                                break;
                            default:
                                break;
                        }

                    }];
}

-(void)back{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

-(void)logout{
    dispatch_async(dispatch_get_main_queue(), ^{
        DRUserModel *userModel = [DRLoginDataModel getUserModel];
        userModel.token = @"";
        [DRLoginDataModel saveUserModel:userModel];
        [DRLoginDataModel setIsLogin:NO];
        UIStoryboard *loginSB = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
        [UIApplication sharedApplication].keyWindow.rootViewController = loginSB.instantiateInitialViewController;
        [[UIApplication sharedApplication].keyWindow makeKeyAndVisible];
    });
}

-(void) goLogin{
//    [self logout];
    [self presentNeedLogin:NO];
}

- (void)goCatering{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.hidesBottomBarWhenPushed = YES;
        UIViewController *vc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DRFoodPairingVC"];
        [self.navigationController pushViewController:vc animated:YES];
    });
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    
    [self.picker dismissViewControllerAnimated:YES completion:nil];
    
    //取得所选取的图片,原大小,可编辑等，info是选取的图片的信息字典
   
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yy-MM-dd-HH-mm-ss"];
    NSString *dateString = [formatter stringFromDate:[NSDate date]];
//    DRUploadModel *uploadModel = nil;
    //获取用户选择或拍摄的是照片还是视频
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        //图片
        DRUploadModel *uploadModel =[DRUploadModel new];
        uploadModel.name = [NSString stringWithFormat:@"%@.png",dateString];
        uploadModel.type = @"image/png";
        UIImage *selectImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(selectImage, 0.1);
        uploadModel.data = imageData;
        [self startUpload:uploadModel];
    }else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        // 视频
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        NSLog(@"压缩前：%f",[self fileSize:videoURL]);
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld_compressedVideo.mp4",time(NULL)]];
        NSLog(@"compressedVideoSavePath : %@",path);
        //压缩
        AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
        if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
            //输出URL
            exportSession.outputURL = [NSURL fileURLWithPath:path];
            //优化网络
            exportSession.shouldOptimizeForNetworkUse = true;
            //转换后的格式
            exportSession.outputFileType = AVFileTypeMPEG4;
            //异步导出
            WEAKSELF
            [exportSession exportAsynchronouslyWithCompletionHandler:^{
                // 如果导出的状态为完成
                STRONGSELF
                if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
//                    [self saveVideo:[NSURL fileURLWithPath:path]];
                    NSURL *sourceURL = [NSURL fileURLWithPath:path];
                    NSString *extension = [sourceURL.absoluteString componentsSeparatedByString:@"."].lastObject;
                    DRUploadModel *uploadModel =[DRUploadModel new];
                    uploadModel.name = [NSString stringWithFormat:@"%@.%@",dateString,extension];
                    uploadModel.type = @"video/mp4";
                    NSData *data = [NSData dataWithContentsOfURL:sourceURL];
                    NSLog(@"%@",uploadModel.name);
                    uploadModel.data = data;
                    [strongSelf startUpload:uploadModel];
                    NSLog(@"压缩后：%f",[strongSelf fileSize:sourceURL]);
                }else{
                    NSLog(@"当前压缩进度:%f",exportSession.progress);
                }
                NSLog(@"%@",exportSession.error);
                
            }];
        }
    }
    
//
//    if (uploadModel) {
//        [self startUpload:uploadModel];
//    }
    _picker = nil;
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.picker dismissViewControllerAnimated:YES completion:nil];
    _picker = nil;
}


-(void) startUpload:(DRUploadModel *) uploadModel {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"Content-Type", nil];
    
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    WEAKSELF
    [manager POST:DRURL(@"index.php/Upload/index") parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:uploadModel.data name:@"file" fileName:uploadModel.name mimeType:uploadModel.type];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        [SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"正在上传"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD showSuccessWithStatus:@"上传成功"];
        NSLog(@"%@",[NSString stringWithFormat:@"getAddress(%@)",[responseObject yy_modelToJSONString]]);
        [weakSelf.webJSContext evaluateScript:[NSString stringWithFormat:@"getAddress(%@)",[responseObject yy_modelToJSONString]]];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"图片上传失败"];
    }];
}

- (CGFloat)fileSize:(NSURL *)path
{
    return [[NSData dataWithContentsOfURL:path] length]/1024.00 /1024.00;
}

-(UIImagePickerController *)picker{
    if (!_picker) {
        _picker = [[UIImagePickerController alloc] init];
        _picker.navigationBar.backIndicatorImage = [UIImage new];
        _picker.navigationBar.backIndicatorTransitionMaskImage = [UIImage new];
        _picker.delegate = self;
    }
    return  _picker;
}

@end


@implementation DRUploadModel


@end
